package com.zzyl.nursing.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.nursing.service.WechatService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
@Service
public class WechatServiceImpl implements WechatService {

    // 登录
    private static final String REQUEST_URL = "https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code";

    // 获取token
    private static final String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";

    // 获取手机号
    private static final String PHONE_REQUEST_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";

    @Value("${wechat.AppID}")
    private String appId;
    @Value("${wechat.AppSecret}")
    private String appSecret;

    @Override
    public String getOpenId(String code) {
        Map<String, Object> paramMap = new HashMap<>();
        //这个是微信小程序的开发者ID
        paramMap.put("appid", appId);
        //这个是微信小程序的开发者密钥
        paramMap.put("secret", appSecret);
        //登录时获取的 code
        paramMap.put("js_code", code);
        //调用hutool的get方法向指定的路径发送请求，并返回结果
        String result = HttpUtil.get(REQUEST_URL, paramMap);
        // 将返回结果转换为JSON对象因为返回结果是json格式的
        JSONObject jsonObject = JSONUtil.parseObj(result);
        //判断对象不为空，则抛出运行时异常，并将错误信息（errmsg）作为异常消息
        if (ObjectUtil.isNotEmpty(jsonObject.getInt("errcode"))){
            // 抛出errcode中的errmsg异常信息
            throw new RuntimeException(jsonObject.getStr("errmsg"));
        }

        //返回openid
        return jsonObject.getStr("openid");
    }


    //获取手机号
    @Override
    public String getPhone(String detailCode) {

        String token = getToken();
        //注意这里不用传开发者ID和密钥
        Map<String, Object> paramMap=new HashMap<>();
        //手机号获取凭证
        paramMap.put("code", detailCode);
        String result = HttpUtil.post(PHONE_REQUEST_URL + token, JSONUtil.toJsonStr(paramMap));
        JSONObject jsonObject = JSONUtil.parseObj(result);
        //判断接口响应是否出错
        if (jsonObject.getInt("errcode")!=0) {
            throw new RuntimeException(jsonObject.getStr("errmsg"));
        }


        return jsonObject.getJSONObject("phone_info").getStr("phoneNumber");
    }

    private String getToken() {
        Map<String, Object> paramMap=new HashMap<>();
        paramMap.put("appid", appId);
        paramMap.put("secret", appSecret);
        String result = HttpUtil.get(TOKEN_URL, paramMap);
        JSONObject jsonObject = JSONUtil.parseObj(result);
        if (ObjectUtil.isNotEmpty(jsonObject.getInt("errcode"))){
            // 抛出errcode中的errmsg异常信息
            throw new RuntimeException(jsonObject.getStr("errmsg"));
        }
        String token = jsonObject.getStr("access_token");
        return token;
    }
}
